import { Ref, ref } from 'vue'
import { PolylineType, LinePathType, DrivingInfoType } from './type'
import markerIcon from '@/assets/image/icon/point.png'
const marketr = ref<any>(null)
const index = ref<number>(0)
const infoWindow = ref<any>(null)
const speed = ref<number>(1000)
export function Driving(
  currentMap: any,
  AMap: any,
  paths: any,
  spd: any,
  drivingInfo: any,
  content: any,
) {
  speed.value = spd
  const polyline = new AMap.Polyline({
    path: paths,
    showDir: true,
    strokeColor: '#00bd01',
    strokeWeight: 6,
    strokeOpacity: 0.8,
  })
  const passedPolyline = new AMap.Polyline({
    map: currentMap,
    strokeColor: '#AF5', //线颜色
    strokeWeight: 6, //线宽
  })
  marketr.value = new AMap.Marker({
    map: currentMap,
    position: paths[0],
    icon: markerIcon,
    offset: new AMap.Pixel(-13, -26),
  })
  polyline.setMap(currentMap)
  // 开始轨迹回放
  marketr.value.on('moving', function (e: any) {
    const i = paths.findIndex(
      (v: any[]) => v[0] == e.passedPos[0] && v[1] == e.passedPos[1],
    )
    index.value = e.passedPath.length
    drivingInfo.currentIndex = i
    drivingInfo.sectionIndex = e.passedPath.length

    passedPolyline.setPath(e.passedPath)
    // passedPolyline.setPath(e.passedPath)
    currentMap.setCenter(e.target.getPosition(), true)
    infoWindowfunc(AMap, currentMap, e.passedPos, content[index.value - 1])
  })
  currentMap.setFitView()
}
export const startAnimation = (paths: any[], num?: number) => {
  if (num == 0) index.value = num
  if (index.value == paths.length) index.value = 0
  marketr.value.moveAlong(paths.slice(index.value), {
    // 每一段的时长
    duration: speed.value, //可根据实际采集时间间隔设置
    // JSAPI2.0 是否延道路自动设置角度在 moveAlong 里设置
    autoRotation: true,
  })
}
export const endAnimation = () => {
  marketr.value && marketr.value.stopMove()
  index.value = 0
}
export const pauseAnimation = () => {
  marketr.value && marketr.value.pauseMove()
}
export const resumeAnimation = () => {
  marketr.value && marketr.value.resumeMove()
}
export const forwardAnimation = (path: any[]) => {
  if (marketr.value) return
  index.value += 1
  marketr.value.setPosition(path[index.value])
}
export const toBackAnimation = (path: any) => {
  if (marketr.value) return
  if (index.value == path.length) {
    index.value = index.value - 2
  } else {
    index.value = index.value - 1
  }
  marketr.value.setPosition(path[index.value])
}
// 窗体
const infoWindowfunc = (AMap: any, currentMap: any, e: any, content: any) => {
  //实例化信息窗体
  infoWindow.value = new AMap.InfoWindow({
    isCustom: true, //使用自定义窗体
    content: '',
    offset: new AMap.Pixel(15, -35),
  })
  infoWindow.value.setContent(content, currentMap.clearInfoWindow())
  infoWindow.value.open(currentMap, [e.lng, e.lat])
}
